<template>
    <div>
        <el-form :inline="true" style="margin-top: 20px;" :model="searchForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="请输入工号:">
                        <el-input v-model="searchForm.wno" placeholder="请输入工号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" style="text-align: right; padding-right: 10px;">
                    <el-button-group>
                        <el-button type="primary" icon="el-icon-search" @click="searchWorker">查询</el-button>
                        <el-button type="primary" icon="el-icon-s-fold" @click="getworker">全部</el-button>
                        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="showAddDialog">添加</el-button>
                    </el-button-group>
                </el-col>
                <el-col :span="4">
                    <el-upload 
                        class="upload-demo" 
                        :action="null"
                        :http-request="handleImport"
                        :show-file-list="false"
                        accept=".xlsx,.xls">
                        <el-button type="primary">导入Excel</el-button>
                    </el-upload>
                    <el-button type="primary" @click="exportExcel">导出 Excel</el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-table :data="workers.list" height="60vh" size="mini" border style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="wno" label="工号" width="80"></el-table-column>
            <el-table-column prop="name" label="姓名" width="100"></el-table-column>
            <el-table-column prop="position" label="职位" width="100"></el-table-column>
            <el-table-column prop="gender" label="性别" width="60"></el-table-column>
            <el-table-column prop="birth" label="出生日期" align="center"></el-table-column>
            <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <el-button type="success" icon="el-icon-check" size="mini" circle @click="viewWorker(scope.row)"></el-button>
                    <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="editWorker(scope.row)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteWorker(scope.row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="workers.total">
            </el-pagination>
        </div>
        
        <!-- 添加/编辑弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
            <el-form :model="workerForm" :rules="rules" ref="workerForm" label-width="80px" class="worker-form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="工号" prop="wno">
                            <el-input v-model="workerForm.wno"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="workerForm.name"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="职位" prop="position">
                            <el-select v-model="workerForm.position" placeholder="请选择职位" style="width: 100%">
                                <el-option label="老板" value="老板"></el-option>
                                <el-option label="经理" value="经理"></el-option>
                                <el-option label="主管" value="主管"></el-option>
                                <el-option label="员工" value="员工"></el-option>
                                <el-option label="实习生" value="实习生"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                            <el-select v-model="workerForm.gender" placeholder="请选择" style="width: 100%">
                                <el-option label="男" value="男"></el-option>
                                <el-option label="女" value="女"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="出生日期" prop="birth">
                            <el-date-picker v-model="workerForm.birth" type="date" placeholder="选择日期" style="width: 100%"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="workerForm.phone"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="地址" prop="address">
                            <el-input v-model="workerForm.address"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitWorker">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getWorkers, addWorker, updateWorker, deleteWorker, exportExcel, importExcel } from '@/api/person'

export default {
    data() {
        return {
            workers: {
                list: [],
                total: 0
            },
            searchForm: {
                wno: ''
            },
            page: 1,
            pageSize: 10,
            dialogVisible: false,
            dialogTitle: '',
            workerForm: {
                id: null,
                wno: '',
                name: '',
                position: '',
                gender: '',
                birth: '',
                phone: '',
                address: ''
            },
            rules: {
                wno: [{ required: true, message: '请输入工号', trigger: 'blur' }],
                name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                position: [{ required: true, message: '请输入职位', trigger: 'blur' }]
            }
        }
    },
    mounted() {
        this.getworker();
    },
    methods: {
        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.pageSize = val;
            this.getworker();
        },
        // 处理页码变化
        handleCurrentChange(val) {
            this.page = val;
            this.getworker();
        },
        // 格式化日期为 YYYY-MM-DD
        formatDate(date) {
            if (!date) return '';
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        getworker() {
            getWorkers({
                page: this.page,
                page_size: this.pageSize
            })
                .then(response => {
                    if (response && response.code === 1) {
                    // 格式化日期
                        const data = response.data;
                    data.list = data.list.map(worker => ({
                        ...worker,
                        birth: this.formatDate(worker.birth)
                    }));
                    this.workers = data;
                    } else {
                        this.$message.error((response && response.msg) || '获取数据失败');
                    }
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    this.$message.error('获取数据失败');
                });
        },
        searchWorker() {
            if (!this.searchForm.wno) {
                this.page = 1;
                this.getworker();
                return;
            }
            getWorkers({
                wno: this.searchForm.wno,
                page: this.page,
                page_size: this.pageSize
            })
                .then(response => {
                    if (response && response.code === 1) {
                    // 格式化日期
                        const data = response.data;
                    data.list = data.list.map(worker => ({
                        ...worker,
                        birth: this.formatDate(worker.birth)
                    }));
                    this.workers = data;
                    } else {
                        this.$message.error((response && response.msg) || '查询失败');
                    }
                })
                .catch(error => {
                    console.error('查询失败:', error);
                    this.$message.error('查询失败');
                });
        },
        showAddDialog() {
            this.dialogTitle = '添加人员';
            this.workerForm = { id: null, wno: '', name: '', position: '', gender: '', birth: '', phone: '', address: '' };
            this.dialogVisible = true;
        },
        editWorker(row) {
            this.dialogTitle = '编辑人员';
            this.workerForm = { 
                ...row,
                birth: row.birth ? new Date(row.birth) : '' // 转换为Date对象，用于日期选择器
            };
            this.dialogVisible = true;
        },
        viewWorker(row) {
            this.dialogTitle = '查看人员';
            this.workerForm = { 
                ...row,
                birth: row.birth ? new Date(row.birth) : '' // 转换为Date对象，用于日期选择器
            };
            this.dialogVisible = true;
        },
        submitWorker() {
            this.$refs['workerForm'].validate((valid) => {
                if (valid) {
                    // 格式化提交的日期
                    const submitData = {
                        ...this.workerForm,
                        birth: this.formatDate(this.workerForm.birth)
                    };
                    
                    const api = this.workerForm.id ? 
                        updateWorker(this.workerForm.id, submitData) : 
                        addWorker(submitData);
                    
                    api.then(response => {
                        if (response && response.code === 1) {
                            this.$message.success((response && response.msg) || '操作成功');
                        this.dialogVisible = false;
                        // 重置页码到第一页
                        this.page = 1;
                        this.getworker();
                        } else {
                            this.$message.error((response && response.msg) || '操作失败');
                        }
                    })
                    .catch(error => {
                        console.error('操作失败:', error);
                        this.$message.error('操作失败');
                    });
                }
            });
        },
        deleteWorker(row) {
            this.$confirm('确认删除该人员?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteWorker(row.id)
                    .then(response => {
                        if (response && response.code === 1) {
                            this.$message.success((response && response.msg) || '删除成功');
                        // 如果当前页只有一条数据，删除后自动跳转到上一页
                        if (this.workers.list.length === 1 && this.page > 1) {
                            this.page--;
                        }
                        this.getworker();
                        } else {
                            this.$message.error((response && response.msg) || '删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('删除失败:', error);
                        this.$message.error('删除失败');
                    });
            });
        },
        exportExcel() {
            exportExcel()
                .then(response => {
                    // 创建blob对象
                    const blob = new Blob([response.data], { 
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                    })
                    
                    // 创建下载链接
                    const link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = '人员信息表.xlsx'
                    
                    // 触发下载
                    document.body.appendChild(link)
                    link.click()
                    
                    // 清理
                    document.body.removeChild(link)
                    window.URL.revokeObjectURL(link.href)
                    
                    this.$message.success('导出成功')
                })
                .catch(error => {
                    console.error('导出失败:', error)
                    this.$message.error('导出失败')
                })
        },
        // 处理Excel导入
        handleImport(options) {
            const formData = new FormData()
            formData.append('file', options.file)
            
            importExcel(formData)
                .then(response => {
                    if (response && response.code === 1) {
                        this.$message.success(response.msg || '导入成功')
                        this.getworker() // 刷新列表
                    } else {
                        this.$message.error((response && response.msg) || '导入失败')
                    }
                })
                .catch(error => {
                    console.error('导入失败:', error)
                    this.$message.error('导入失败')
                })
        },
    }
}
</script>

<style>
html,
body,
.el-container {
    margin: 0;
    padding: 0;
    height: 100%;
    background-color: #f5f7fa;
}

.el-header {
    background-color: #fff;
    color: #333;
    text-align: left;
    line-height: 80px;
    font-size: 25px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.el-footer {
    background-color: #fff;
    color: #333;
    text-align: center;
    line-height: 30px;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
}

.el-aside {
    background-color: #fff;
    color: #333;
    text-align: left;
    line-height: 200px;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.05);
}

.el-main {
    background-color: #f5f7fa;
    color: #333;
    padding: 20px;
}

.el-row {
    margin-bottom: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    &:last-child {
        margin-bottom: 0;
    }
}

.el-table {
    margin-top: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    th {
        background-color: #f5f7fa !important;
        color: #606266;
        font-weight: 600;
    }
    
    td {
        padding: 12px 0;
    }
}

.el-button {
    border-radius: 4px;
    transition: all 0.3s;
    
    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
}

.el-button-group {
    .el-button {
        margin-right: 8px;
    }
}

.el-form-item {
    margin-bottom: 20px;
}

.el-input__inner {
    border-radius: 4px;
    transition: all 0.3s;
    
    &:focus {
        border-color: #409EFF;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
}

.el-dialog {
    border-radius: 8px;
    overflow: hidden;
    
    .el-dialog__header {
        background-color: #f5f7fa;
        padding: 15px 20px;
        margin: 0;
    }
    
    .el-dialog__body {
        padding: 5px 20px;
    }
    
    .el-dialog__footer {
        padding: 10px 20px;
        border-top: 1px solid #ebeef5;
    }
}

.upload-demo {
    display: inline-block;
    margin-right: 10px;
}

.el-table-column--selection .cell {
    padding-left: 20px;
}

.el-table-column--index .cell {
    padding-left: 20px;
}

.el-table .cell {
    padding: 0 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
    padding: 10px 0;
}

.el-pagination {
    padding: 0;
    font-weight: normal;
}

.el-pagination .el-select .el-input {
    width: 120px;
}

.el-pagination .el-pagination__sizes {
    margin-right: 16px;
}

.el-pagination .el-pagination__jump {
    margin-left: 16px;
}

.worker-form {
    padding: 10px;
}

.worker-form .el-form-item {
    margin-bottom: 15px;
}

.worker-form .el-input,
.worker-form .el-select,
.worker-form .el-date-picker {
    width: 100%;
}
</style>